<?php


namespace App\Http\Controllers\Admin\Game;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Jobs\RongCloud\RoomPushJob;
use App\Models\MainDB\GameSugarRecord;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SugarController extends BaseController
{
    // 获取糖果配置
    public function getConfig()
    {
        $data = app('model_game_sugar_config')
            ->from('ln_game_sugar_config as config')
            ->where([['config.is_delete', '=', 0]])
            ->leftJoin('ln_gift as g', 'g.id', '=', 'config.gift_id')
            ->selectRaw('config.id, config.name, config.type, config.status, config.cost, config.join_num, config.gift_num, config.rule, config.is_show, config.show_start_time, config.show_end_time, g.id as gift_id, g.name as gift_name')
            ->get();
        return Response::sendData($data);
    }

    // 修改糖果配置
    public function updateConfig(Request $request)
    {
        // 游戏开关
        $status = $request->input('status', -1);
        // 修改配置
        $configId = $request->input('id', 0);
        if (empty($configId)) {
            throw new BasicException(10001, '非法访问');
        }
        $userNum = $request->input('join_num', 0);
        if($userNum < 3){
            throw new BasicException(10001, '人数不合法');
        }
        $sugarNum = $request->input('sugar_num', 0);
        $cost = $request->input('cost', 0);
        $rule = $request->input('rule', -1);
        // new content
        $is_show = $request->input('is_show', 0);
        $show_start_time = $request->input('show_start_time', 0);
        $show_end_time = $request->input('show_end_time', 0);
        if ($show_start_time != 0 && $show_end_time != 0) {
            if ($show_start_time > $show_end_time) {
                throw new BasicException(10001, '开始时间必须大于结束时间');
            }
        }

        $update = ['update_time' => time()];
        // 判断是否是后两场 只有后两场改这个状态 new todo 新增糖果优化
        if ($configId != 1) {
            $update['is_show'] = $is_show;
            $update['show_start_time'] = $show_start_time;
            $update['show_end_time'] = $show_end_time;
        }
        if (!empty($userNum)) {
            $update['join_num'] = $userNum;
        }
        if($sugarNum < 1 || $cost < 1){
            throw new BasicException('糖果数量与押金设置数量不符');
        }
        if (!empty($sugarNum) || !empty($cost)) {
            if ($sugarNum != $cost) {
                throw new BasicException(10001, '糖果数与押金不相等');
            }
            $update['gift_num'] = $sugarNum;
            $update['cost'] = $cost;
        }
        if (in_array($rule, [0, 1])) {
            $update['rule'] = $rule;
        }
        DB::beginTransaction();
        try {
            app('model_game_sugar_config')->where([['id', '=', $configId]])->update($update);
            if (in_array($status, [0, 1])) { // 处理游戏开关
                $setStatus = $this->setGameStatus($status);
            }
            if ($configId != 1 && in_array($is_show, [0, 1])) { // 处理游戏开关
                $setStatus = $this->setGameShow($is_show,$configId);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(10001, '修改失败' . $e->getMessage());
        }
        DB::commit();
        if (isset($setStatus)) {
            app('redis')->set('game:sugar:status', $status);
            // 推送
            $topic = 'room';
            $content = [
                'name' => $topic,
                'data' => [
                    'type' => 3001,
                    'time' => (int)(microtime(true) * 1000),
                    'msg' => ['action' => $status],
                ],
            ];
            $roomPushJob = new RoomPushJob('system', $topic, $content);
            dispatch($roomPushJob);
        }
        return Response::sendData($update);
    }


    // 信息
    public function info(Request $request)
    {
        $type = $request->input('type', 0);
        $gameSn = $request->input('game_sn', 0);
        $createStartTime = $request->input('create_start_time', 0);
        $createEndTime = $request->input('create_end_time', 0);
        $finishStartTime = $request->input('finish_start_time', 0);
        $finishEndTime = $request->input('finish_end_time', 0);
        $limit = $request->input('per_page', 10);
        if (empty($type)) {
            throw new BasicException(10001, '非法请求');
        }
        $condition = [['type', '=', $type]];
        if (!empty($gameSn)) {
            $condition[] = ['game_sn', '=', $gameSn];
        }
        if (!empty($createStartTime)) {
            $condition[] = ['create_time', '>=', $createStartTime];
        }
        if (!empty($createEndTime)) {
            $condition[] = ['create_time', '<=', $createEndTime];
        }
        if (!empty($finishStartTime)) {
            $condition[] = ['end_time', '>=', $finishStartTime];
        }
        if (!empty($finishEndTime)) {
            $condition[] = ['end_time', '<=', $finishEndTime];
        }
        //        DB::enableQueryLog();
        $data = app('model_game_sugar_info')->getListByCondition($condition, "id,status,rule,join_num as allow_num,gift_num,cost,game_sn,FROM_UNIXTIME(create_time) as start_time,IF(end_time>0,FROM_UNIXTIME(end_time),0) as end_time", $limit);
        //        dump(DB::getQueryLog());
        if (empty($data['data'])) {
            return Response::sendData($data);
        }
        // 获取当前页游戏参与人数
        $gameIdArr = array_column($data['data'], 'id');
        $joinUserNumArr = [];
        if ($gameIdArr) {
            $joinUserNumInfo = app('model_game_sugar_join')->getJoinGameUserByManyGameId($gameIdArr);
            if ($joinUserNumInfo) {
                $joinUserNumArr = array_column($joinUserNumInfo, 'num', 'game_id');
            } else {
                $joinUserNumArr = [];
            }
        }
        foreach ($data['data'] as &$v) {
            $v['join_num'] = $joinUserNumArr[$v['id']] ?? 0;
        }
        return Response::sendData($data);
    }

    // 详情
    public function detail(Request $request)
    {
        $gameId = $request->input('id', 0);
        if ($gameId <= 0) {
            throw new BasicException(10001, '非法访问');
        }
        // 获取游戏信息
        $data = app('model_game_sugar_info')->getDetailByCondition(['id' => $gameId], "id,status,rule,join_num as allow_num,gift_num,cost,game_sn,FROM_UNIXTIME(create_time) as start_time,IF(end_time>0,FROM_UNIXTIME(end_time),0) as end_time");
        if (empty($data)) {
            return Response::sendData([]);
        }
        // 状态不同获取的参与用户方式不同.
        switch ($data['status']) {
            case 2: // 完成
                $users = app('model_game_sugar_record')->getRecordUserDetailByCondition(['game_id' => $gameId]);
                break;
            default: // 进行中
                $users = app('model_game_sugar_join')->getJoinUserDetail(['game_id' => $gameId]);
                break;
        }
        $data['join_num'] = count($users);
        $data['users'] = $users;
        return Response::sendData($data);
    }

    // 用户信息
    public function userGameInfo(Request $request)
    {
        $condition = [];
        $limit = $request->input('per_page', 10);
        $searchUserId = $request->input('user_id',  0);
        $searchNickname = $request->input('nickname', '');
        $searchMobile = $request->input('mobile', '');
        if(!empty($searchUserId)){
            $condition[] = ['r.user_id', '=', $searchUserId];
        }
        if(!empty($searchMobile)){
            $userId = app('model_user')->getFieldValue('user_id', [ ['mobile', '=', $searchMobile] ]);
            if(!empty($userId)){
                $condition[] = ['r.user_id', '=', $userId];
            }
        }
        if(!empty($searchNickname)){
            $condition[] = ['ud.nickname', 'like', "$searchNickname%"];
        }
        $result = app('model_game_sugar_record')->getAllUserProfitInfo($condition, $limit);
        return Response::sendData($result);
    }

    // 数据列表
    public function dataList()
    {
        //        app('repo_game_sugar_statistics')->dayDataStatistics('2021-06-23');
        //        return 1;
        $today = date("Y-m-d");
        $gameTitle = app('model_game_sugar_config')->where([['is_delete', '=', 0]])->selectRaw('type,name')->get()->toArray();
        $gameTitleArr = array_column($gameTitle, 'name', 'type');
        $result = [
            'title' => [
                'first' => $gameTitleArr[1] ?? '新秀赛',
                'second' => $gameTitleArr[2] ?? '赛',
                'third' => $gameTitleArr[3] ?? '新秀赛',
            ],
            'total' => app('repo_game_sugar_statistics')->getTotalInfo(),
            'chart' => app('repo_game_sugar_statistics')->getHistorySugarInfoByDate($today, 12, true),
        ];
        return Response::sendData($result);
    }

    public function setGameStatus($status)
    {
        if ($status == 0) { // 关闭
            $gameMaxIdArr = app('model_game_sugar_info')->groupBy('type')->selectRaw('max(id) as id')->get()->toArray();
            if (empty($gameMaxIdArr)) {
                return true;
            }
            $gameMaxIdArr = array_column($gameMaxIdArr, 'id');
            $gameMaxInfo = app('model_game_sugar_info')->whereIn('id', $gameMaxIdArr)->selectRaw('id,type,cost,end_time,join_num')->get()->toArray();
            if (empty($gameMaxInfo)) {
                return true;
            }
            $join_redis_key = 'game:sugar:join:user:';
            $allow_redis_key = 'game:sugar:allow:join:num:';
            $redis = app('redis');
            foreach ($gameMaxInfo as $v) {
                if ($v['end_time'] > 0) { // 已结束.不处理
                    continue;
                }
                $joinUserArr = app('model_game_sugar_join')->where([['game_id', '=', $v['id']]])->pluck('user_id')->toArray(); // 获取加入用户
                if (empty($joinUserArr)) {
                    continue;
                }
                foreach ($joinUserArr as $joinUserId) {
                    //账户修改并记录日志
                    app('repo_account')->change($joinUserId, 53, abs($v['cost']), '抢糖果押金返回', 0);
                }
                app('model_game_sugar_info')->where([['id', '=', $v['id']]])->update(['status' => -2, 'end_time' => time()]); // 游戏关闭
                // 删除加入人数
                app('model_game_sugar_join')->where([['game_id', '=', $v['id']]])->delete();
                $redis->del($join_redis_key.$v['id']);
                $redis->set($allow_redis_key.$v['id'],$v['join_num']);
            }
        } else if($status == 1){
            $gameMaxIdArr = app('model_game_sugar_info')->groupBy('type')->selectRaw('max(id) as id')->get()->toArray();
            if (empty($gameMaxIdArr)) {
                return true;
            }
            $gameMaxIdArr = array_column($gameMaxIdArr, 'id');
            $gameMaxInfo = app('model_game_sugar_info')->whereIn('id', $gameMaxIdArr)->selectRaw('id,type,cost,end_time,join_num')->get()->toArray();
            if (empty($gameMaxInfo)) {
                return true;
            }
            foreach ($gameMaxInfo as $v) {
                app('model_game_sugar_info')->where([['id', '=', $v['id']]])->update(['status' => 1, 'end_time' => 0]); // 游戏开启
            }
        }
        app('model_game_sugar_config')->where([['is_delete', '=', 0]])->update(['status' => $status]); // 全游戏配置状态更新
        app('redis')->set('game:sugar:info', ''); // 清除缓存
        return true;
    }

    public function setGameShow($show,$configId)
    {
        if ($show == 0) { // 关闭
            $gameMaxIdArr = app('model_game_sugar_info')->where([['type', '=', $configId]])->groupBy('type')->selectRaw('max(id) as id')->get()->toArray();
            if (empty($gameMaxIdArr)) {
                return true;
            }
            $gameMaxIdArr = array_column($gameMaxIdArr, 'id');
            $gameMaxInfo = app('model_game_sugar_info')->whereIn('id', $gameMaxIdArr)->selectRaw('id,type,cost,end_time,join_num')->get()->toArray();
            if (empty($gameMaxInfo)) {
                return true;
            }
            $join_redis_key = 'game:sugar:join:user:';
            $allow_redis_key = 'game:sugar:allow:join:num:';
            $redis = app('redis');
            foreach ($gameMaxInfo as $v) {
                if ($v['end_time'] > 0) { // 已结束.不处理
                    continue;
                }
                $joinUserArr = app('model_game_sugar_join')->where([['game_id', '=', $v['id']]])->pluck('user_id')->toArray(); // 获取加入用户
                if (empty($joinUserArr)) {
                    continue;
                }
                foreach ($joinUserArr as $joinUserId) {
                    //账户修改并记录日志
                    app('repo_account')->change($joinUserId, 53, abs($v['cost']), '抢糖果押金返回', 0);
                }
                app('model_game_sugar_info')->where([['id', '=', $v['id']]])->update(['status' => -2, 'end_time' => time()]); // 游戏关闭
                // 删除加入人数
                app('model_game_sugar_join')->where([['game_id', '=', $v['id']]])->delete();
                $redis->del($join_redis_key.$v['id']);
                $redis->set($allow_redis_key.$v['id'],$v['join_num']);
            }
        } else if($show == 1){
            $gameMaxIdArr = app('model_game_sugar_info')->where([['type', '=', $configId]])->groupBy('type')->selectRaw('max(id) as id')->get()->toArray();
            if (empty($gameMaxIdArr)) {
                return true;
            }
            $gameMaxIdArr = array_column($gameMaxIdArr, 'id');
            $gameMaxInfo = app('model_game_sugar_info')->whereIn('id', $gameMaxIdArr)->selectRaw('id,type,cost,end_time,join_num')->get()->toArray();
            if (empty($gameMaxInfo)) {
                return true;
            }
            foreach ($gameMaxInfo as $v) {
                app('model_game_sugar_info')->where([['id', '=', $v['id']]])->update(['status' => 1, 'end_time' => 0]); // 游戏开启
            }
        }
        app('model_game_sugar_config')->where([['is_delete', '=', 0],['id', '=', $configId]])->update(['is_show' => $show]); // 全游戏配置状态更新
        app('redis')->set('game:sugar:info', ''); // 清除缓存
        return true;
    }
}

